 //
//  BCNetAPIClient.m
//  BCShop
//
//  Created by sheweicai on 15/6/1.
//  Copyright (c) 2015年 美丽点击. All rights reserved.
//
#define REQUEST_SUCCESS  1001
#define STR_LOADING @"加载中..."

#import "BCNetAPIClient.h"
#import "NSObject+MJKeyValue.h"
#import "SVProgressHUD.h"
#import "Define.h"
#import "AppLocalManager.h"
#import "LoginViewController.h"

static BCNetAPIClient *_sharedClient = nil;
//@interface BCNetAPIClient()<LoginViewControllerDelegate>
//
//@end
@implementation BCNetAPIClient

+ (BCNetAPIClient *)sharedJsonClient {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[BCNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:@""]];
         [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    });
    
    return _sharedClient;
}

- (void)refreshToken{
    [self setToken];
}

- (id)initWithBaseURL:(NSURL *)url {
    
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html",@"multipart/form-data",@"image/jpeg",@"image/png",nil];
    [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [self setToken];
    
    [self.requestSerializer setTimeoutInterval:10];
    
    //      AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    //    self.requestSerializer.securityPolicy = securityPolicy;
    //    NSLog(@"这是后台需要拼接的字符串--%@--这是之前的token##%@",strone,GETACCESS_TOKEN);
    
    
    self.securityPolicy.allowInvalidCertificates = YES;
    
    return self;
}

- (void)setToken{
    //新增请求头Authorization
    NSString *str=@"Bearer ";
    NSString *strone;
    
    if (GETACCESS_TOKEN!=nil) {
        NSLog(@"%@",GETACCESS_TOKEN);
        strone=[str stringByAppendingString:GETACCESS_TOKEN];
        [self.requestSerializer setValue:strone forHTTPHeaderField:@"Authorization"];
    }
    
}

- (void)requestJsonDataWithPath:(NSString *)aPath
                     withParams:(NSDictionary*)params
                 withMethodType:(NetworkMethod)NetworkMethod
                       andBlock:(void (^)(id data, NSError *error,AFHTTPRequestOperation *operation))block{
    
    
    
    //log请求数据
  //  NSLog(@"\n===========request===========\n地址：%@\n:参数：%@", aPath, params);
    //aPath = [aPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    aPath=[aPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //发起请求
    switch (NetworkMethod) {
        case Get:{
            [self GET:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                NSLog(@"\n成功响应路径：%@===========response===========:\n成功响应对象：%@", aPath, responseObject);
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error,operation);
                }else{
                    block(responseObject, nil ,operation);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             //   NSLog(@"\n失败响应路径：%@===========response===========:\n失败响应信息：%@", aPath, error);
                block(nil, error, operation);
            }];
            break;
        }
        case Post:{
            [self POST:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"%@",operation.responseString);
                NSLog(@"\n成功响应路径：%@===========response===========:\n成功响应对象：%@", aPath, responseObject);
                id error = [self handleResponse:responseObject];
                if (error)
                {
                    block(nil, error ,operation);
                }
                
                block(responseObject, nil, operation);
                //                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                block(nil,error,operation);
                
//                NSLog(@"\n失败响应路径：%@===========response===========:\n失败响应信息：%@", aPath, error);
            }];
            break;
        }
        case Put:{
            [self PUT:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"\n%@===========response===========:\n%@", aPath, responseObject);
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error,operation);
                }else{
                    block(responseObject, nil, operation);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                NSLog(@"\n%@===========response===========:\n%@", aPath, error);
                block(nil, error, operation);
            }];
            break;}
        case Delete:{
            [self DELETE:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
 //               NSLog(@"\n%@===========response===========:\n%@", aPath, responseObject);
                id error = [self handleResponse:responseObject];
                if (error) {
                    block(nil, error, operation);
                }else{
                    block(responseObject, nil, operation);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                NSLog(@"\n%@===========response===========:\n%@", aPath, error);
                block(nil, error, operation);
            }];}
        default:
            break;
    }
}

- (void)requestJsonDataWithUrl:(NSString *)requestUrl
                    withParams:(NSDictionary*)params
                withMethodType:(NetworkMethod)NetworkMethod showProgress:(BOOL)showProgress
         showNetworkErrorAlert:(BOOL)showAlert onCompletion:(RequestCompleteBlock)completionBlock onError:(RequestErrorBlock)errorBlock{
    //log请求数据
 //   NSLog(@"\n===========request===========\n%@:\n%@", requestUrl, params);
    requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    if (showProgress) {
        [SVProgressHUD showWithStatus:STR_LOADING];
    }
    
    //发起请求
    switch (NetworkMethod) {
        case Get:{
            [self GET:requestUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
  //              NSLog(@"--链接成功\n%@===========response===========:成功详情\n%@", requestUrl, responseObject);
                NSError *errorInfo = [self convertResponse:responseObject showProgress:showProgress showNetworkErroAlert:showAlert];
                if (!errorInfo) {
                    completionBlock(responseObject);
                }else{
                    errorBlock(errorInfo);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         //       NSLog(@"链接失败\n%@===========response===========:失败详情\n%@", requestUrl, error);
                errorBlock(error);
            }];
            break;
        }
        case Post:{
            [self POST:requestUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"--链接成功\n%@===========response===========:成功详情\n%@", requestUrl, responseObject);
                NSError *error = [self convertResponse:responseObject showProgress:showProgress showNetworkErroAlert:showAlert];
                if (!error) {
                    if ([requestUrl isEqualToString:@""]) {
                        [BCNetAPIClient saveCookieData];
                    }
                    completionBlock(responseObject);
                }else{
                    errorBlock(error);
                }
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                if (error.code==-1001) {
                    [SVProgressHUD showErrorWithStatus:@"网络超时，请稍后再试"];
                }
          //      NSLog(@"\n%@===========response===========:\n%@", requestUrl, error);
                errorBlock(error);
            }];
            break;
        }
        case Put:{
            [self PUT:requestUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //        NSLog(@"\n%@===========response===========:\n%@", requestUrl, responseObject);
                NSError *error = [self convertResponse:responseObject showProgress:showProgress showNetworkErroAlert:showAlert];
                if (!error) {
                    completionBlock(responseObject);
                }else{
                    errorBlock(error);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      //          NSLog(@"\n%@===========response===========:\n%@", requestUrl, error);
                errorBlock(error);
            }];
            break;
        }
        case Delete:{
            [self DELETE:requestUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
       //         NSLog(@"\n%@===========response===========:\n%@", requestUrl, responseObject);
                NSError *error = [self convertResponse:responseObject showProgress:showProgress showNetworkErroAlert:showAlert];
                if (!error) {
                    completionBlock(responseObject);
                }else{
                    errorBlock(error);
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //            NSLog(@"\n%@===========response===========:\n%@", requestUrl, error);
                errorBlock(error);
            }];
        }
        default:
            break;
    }
}




+ (void)saveCookieData{
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie *cookie in cookies) {
        // Here I see the correct rails session cookie
 //       NSLog(@"\nSave cookie: \n====================\n%@", cookie);
    }
    
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject: cookiesData forKey: Code_CookieData];
    [defaults synchronize];
}
+ (void)removeCookieData{
    NSURL *url = [NSURL URLWithString:@""];
    if (url) {
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
        for (int i = 0; i < [cookies count]; i++) {
            NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i];
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
 //           NSLog(@"\nDelete cookie: \n====================\n%@", cookie);
        }
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:Code_CookieData];
    [defaults synchronize];
}

-(id)convertResponse:(id)response showProgress:(BOOL)showProgress showNetworkErroAlert:(BOOL)showErroAlert{
    if (showProgress) {
        [SVProgressHUD dismiss];
    }
    NSError *error = nil;
    int resultCode = [[response objectForKey:@"code"] intValue];
    if (resultCode != REQUEST_SUCCESS) {
        error = [NSError errorWithDomain:@"" code:resultCode userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[response objectForKey:@"msg"],@"msg", nil]];
        if (showErroAlert) {
            [SVProgressHUD showErrorWithStatus:[response objectForKey:@"msg"]];
        }
    }
    return error;
}

-(id)handleResponse:(id)responseJSON{
    NSError *error = nil;
    //code为非0值时，表示有错
    NSNumber *resultCode = [responseJSON valueForKeyPath:@"Status"];
    
    if (resultCode.intValue != 1) {
        error = [NSError errorWithDomain:@"错误" code:resultCode.intValue userInfo:responseJSON];
        
        if (resultCode.intValue == 1000) {//用户未登录
        }
    }
    //    数据为空时，构造error提示
    //    id resultData = [responseJSON valueForKeyPath:@"data"];
    //    if (!resultData) {
    //        error = [NSError errorWithDomain:kNetPath_Code_Base code:resultCode.intValue userInfo:
    //                          [NSDictionary dictionaryWithObject:
    //                           [NSDictionary dictionaryWithObject:@"获取的数据为空" forKey:@"tipMsg"] forKey:@"msg"]];
    //    }
    return nil;
}

+(void)uploadImage:(NSString *)url andParameters:(NSDictionary *)parameters andImage:(UIImage *)image progress:(void(^)(NSProgress *progress))progress success:(void (^)(id responseObject))success failure:(void (^)(NSError *failure))failure{
    
    AFHTTPSessionManager *sessionManager=[AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"application/json"];
    
    NSString *str=@"Bearer ";
    
    NSString *strone;
    if (GETACCESS_TOKEN!=nil) {
        NSLog(@"%@",GETACCESS_TOKEN);
        strone=[str stringByAppendingString:GETACCESS_TOKEN];
    }
    [sessionManager.requestSerializer setValue:strone forHTTPHeaderField:@"Authorization"];
    
    sessionManager.requestSerializer.timeoutInterval=20.f;
    
    [sessionManager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //搞成PNG的格式
        //NSData *imageData = UIImagePNGRepresentation(image);
        NSData *imageData = UIImageJPEGRepresentation(image,0.5);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        // 上传图片，以文件流的格式
        //[formData appendPartWithFileData:imageData name:@"imageFile" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:imageData name:@"imageFile" fileName:fileName mimeType:@"image/JPEG"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"上传成功:%@",responseObject);
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"上传失败:%@",error);
        failure(error);
        
    }];
   
    
}

#pragma mark - 上传视频
+ (void)upLoadVideoWithOption:(NSDictionary *)para withInferface:(NSString *)requestURL videoPath:(NSString *)videoPath uploadSuccess:(void (^)(AFHTTPRequestOperation * , id))success uoloadFailure:(void (^)(AFHTTPRequestOperation *, NSError *))failure progress:(void (^)(float))progress {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str=@"Bearer ";
    
    NSString *strone;
    if (GETACCESS_TOKEN!=nil) {
        NSLog(@"%@",GETACCESS_TOKEN);
        strone=[str stringByAppendingString:GETACCESS_TOKEN];
    }
    [manager.requestSerializer setValue:strone forHTTPHeaderField:@"Authorization"];
    
    manager.requestSerializer.timeoutInterval=20.f;
    
    //text/plain
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    AFHTTPRequestOperation *opera = [manager POST:requestURL parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        NSData *videoData = [NSData dataWithContentsOfFile:videoPath];
        [formData appendPartWithFileData:videoData name:@"video000" fileName:@"video000.mp4" mimeType:@"video/mpeg4"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        success(operation,dict);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        failure (operation,error);
    }];
    
    [opera setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        CGFloat xx = totalBytesExpectedToWrite;
        CGFloat yy = totalBytesWritten;
        CGFloat pro = yy/xx;
        progress(pro);
    }];
    [opera start];
}

//12.19 test
+ (void)postWithImgPath:(NSString *)path
                 params:(NSDictionary *)params
                 images:(NSArray *)images
                success:(void(^)(id responseObject))success
                failure:(void(^)(NSError *error))failure {
    AFHTTPRequestOperationManager *sessionManager=[AFHTTPRequestOperationManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"application/json"];
    
    NSString *str=@"Bearer ";
    
    NSString *strone;
    if (GETACCESS_TOKEN!=nil) {
        NSLog(@"%@",GETACCESS_TOKEN);
        strone=[str stringByAppendingString:GETACCESS_TOKEN];
    }
    [sessionManager.requestSerializer setValue:strone forHTTPHeaderField:@"Authorization"];
    
    sessionManager.requestSerializer.timeoutInterval=20.f;
            
            [sessionManager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                for (NSUInteger idx = 0; idx < images.count; idx ++) {
                    UIImage *image = images[idx];
                    NSData *imageData = UIImageJPEGRepresentation(image,0.5);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmmss";
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
                // 上传图片，以文件流的格式
                //[formData appendPartWithFileData:imageData name:@"imageFile" fileName:fileName mimeType:@"image/png"];
                    [formData appendPartWithFileData:imageData name:@"imageFile" fileName:fileName mimeType:@"image/JPEG"];
                }
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"上传成功:%@",responseObject);
                success(responseObject);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"上传失败:%@",error);
                failure(error);
                
            }];
}
//videoStr	__NSCFString *	@"file:///private/var/mobile/Containers/Data/Application/7F8568F8-5E3B-4D1F-A3C6-5C1F9BF079AB/tmp/.mp4"	0x00000001704ec000
+ (void)PostVideosAndImages:(NSString *)path parameters:params imageArray:(NSArray *)imagesArr videoArray:(NSString *)videoStr success:(void(^)(id responseObjecet))success failure:(void(^)(NSError *error))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer    = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes  = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html",@"multipart/form-data",@"image/jpeg",@"image/png",@"video/mpeg4",nil];
    NSString *str=@"Bearer ";
    NSString *strone;
    if (GETACCESS_TOKEN!=nil) {
        NSLog(@"%@",GETACCESS_TOKEN);
        strone=[str stringByAppendingString:GETACCESS_TOKEN];
    }
    [manager.requestSerializer setValue:strone forHTTPHeaderField:@"Authorization"];
    manager.requestSerializer.timeoutInterval = 20.f;
    
    [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (imagesArr.count != 0) {
            
            for (NSUInteger idx = 0; idx < imagesArr.count; idx ++) {
                
                NSDate *date = [NSDate new];
                NSDateFormatter *df = [[NSDateFormatter alloc]init];
                [df setDateFormat:@"yyyyMMddHHmmss"];
                [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
                UIImage *image   = imagesArr[idx];
                NSData *imageData = UIImageJPEGRepresentation(image,0.5);
                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"header%zi", idx + 1 ] fileName:[NSString stringWithFormat:@"%@%zi.jpg", [df stringFromDate:date], idx + 1 ] mimeType:@"image/jpg"];
            }
        }
        
        if (videoStr) {
            NSDate *date = [NSDate new];
            NSDateFormatter *df = [[NSDateFormatter alloc]init];
            [df setDateFormat:@"yyyyMMddHHmmss"];
            [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
            NSData *videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:videoStr]];
            [formData appendPartWithFileData:videoData name:[NSString stringWithFormat:@"video%@",[df stringFromDate:date]] fileName:@"video.mp4" mimeType:@"video/quicktime"];
        }
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

+ (void)PostVideosAndImages:(NSString *)path parameters:params videoArray:(NSString *)videoStr success:(void(^)(id responseObjecet))success failure:(void(^)(NSError *error))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer    = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes  = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html",@"multipart/form-data",@"image/jpeg",@"image/png",@"video/mpeg4",nil];
    NSString *str=@"Bearer ";
    NSString *strone;
    if (GETACCESS_TOKEN!=nil) {
        NSLog(@"%@",GETACCESS_TOKEN);
        strone=[str stringByAppendingString:GETACCESS_TOKEN];
    }
    [manager.requestSerializer setValue:strone forHTTPHeaderField:@"Authorization"];
    manager.requestSerializer.timeoutInterval = 20.f;
    
    [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (videoStr) {
            NSDate *date        = [NSDate new];
            NSDateFormatter *df = [[NSDateFormatter alloc]init];
            [df setDateFormat:@"yyyyMMddHHmmss"];
            [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
            NSData *videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:videoStr]];
            [formData appendPartWithFileData:videoData name:@"video.mp4" fileName:[NSString stringWithFormat:@"video%@",[df stringFromDate:date]] mimeType:@"video/mpeg4"];
        }

    } success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}



#pragma mark -- LoginViewControllerDelegate
- (void)loginSuccess:(UIView *)view{
    UIView *loginView = view;
    [UIView animateWithDuration:0.3 animations:^{
        loginView.frame = CGRectMake(0, loginView.frame.size.height, loginView.frame.size.width, loginView.frame.size.height);
    }];
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 0.3*NSEC_PER_SEC);
    __weak BCNetAPIClient *weakSelf= self;
    dispatch_after(time, dispatch_get_main_queue(), ^{
        [weakSelf setLoginNull:view];
    });
}

- (void)setLoginNull:(UIView *)view{
    [view removeFromSuperview];
    view = nil;
    
}



@end
